package com.woniuxy.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: 马宇航
 * @Description: TODO
 * @DateTime: 22/10/21/0021 14:22
 * @Component: 成都蜗牛学苑
 **/
@Configuration
public class ReturnsCallbackConfig {
    @Bean
    public RabbitTemplate.ReturnsCallback returnsCallback(RabbitTemplate rabbitTemplate){
        return new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                System.err.println("消息被退回："+returned.getMessage().toString());
                System.err.println("消息"+new String(returned.getMessage().getBody(), StandardCharsets.UTF_8));
                System.err.println("Routingkey："+returned.getRoutingKey());
                System.err.println("获得消费者全局唯一标签："+
                        returned.getMessage().getMessageProperties()
                                .getHeader("spring_returned_message_correlation"));
                //模拟交换机发送到某个队列失败后，重新发送给另外一个队列，或者另外一个交换机
                rabbitTemplate.convertAndSend("fanoutExchange","",returned.getMessage());
            }
        };
    }
}
